package com.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.pojo.ProductInfo;
import com.ssm.pojo.vo.ProductInfoVo;
import com.ssm.service.ProductInfoService;
import com.ssm.utils.FileNameUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/prod")
public class ProductInfoAction {
    //每页显示的记录数
    public static final int PAGE_SIZE = 5;
    //ajax异步上传的文件名
    String fileName = "";

    @Autowired
    private ProductInfoService productInfoService;

    //不分页显示所有
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request) {
        List<ProductInfo> productInfos = productInfoService.getAll();
        request.setAttribute("productInfos", productInfos);
        return "product";
    }

    //显示第一页的数据
    @RequestMapping("/split")
    public String split(HttpServletRequest request) {
        PageInfo info = productInfoService.splitPage(1, PAGE_SIZE);
        request.setAttribute("info", info);

        return "product";
    }

    //ajax分页翻页处理
    @ResponseBody
    @RequestMapping("/ajaxSplit")
    public void ajaxSplit(ProductInfoVo vo, HttpSession session) {
        PageInfo info = productInfoService.splitPageVo(vo, PAGE_SIZE);
        session.setAttribute("info", info);
    }
//    //多条件查询
//    @RequestMapping("/condition")
//    @ResponseBody
//    public void condition(ProductInfoVo vo,HttpSession session) {
//        List<ProductInfo> list = productInfoService.selectCondition(vo);
//        session.setAttribute("list",list);
//    }

    //异步ajax文件上传处理
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage, HttpServletRequest request) {
        //提取生成文件名UUID+文件后缀名
        fileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目中图片的存储路径
        String path = request.getServletContext().getRealPath("/image_big");
        //转存
        try {
            pimage.transferTo(new File(path + File.separator + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客户端json对象，封装图片的路径，为了在页面实现回显
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imgurl", fileName);

        return jsonObject.toString();
    }

    //增加商品
    @RequestMapping("/save")
    public String save(ProductInfo info, HttpServletRequest request) {
        info.setpImage(fileName);
        info.setpDate(new Date());

        int num = -1;
        try {
            num = productInfoService.save(info);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (num > 0) {
            request.setAttribute("msg", "添加商品成功");
        } else {
            request.setAttribute("msg", "添加商品失败");
        }
        //清空fileName变量的内容，为了不影响下次增加或修改的异步ajax
        fileName = "";
        return "forward:/prod/split";
    }

    @RequestMapping("/one")
    public String one(int pid, Model model) {
        ProductInfo info = productInfoService.getById(pid);
        model.addAttribute("prod", info);

        return "update";
    }

    @RequestMapping("/update")
    public String update(ProductInfo info, HttpServletRequest request) {
        //如果上传过图片，则fileName里有上传上来的图片名称，如果没有使用过异步ajax上传过图片，则fileName等于空
        if (!fileName.equals("")) {
            info.setpImage(fileName);
        }
        //完成更新操作
        int num = -1;
        try {
            num = productInfoService.update(info);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if ((num > 0)) {
            request.setAttribute("msg", "更新成功");
        } else {
            request.setAttribute("msg", "更新失败");
        }
        //处理完更新后，fileName要进行清空，防止影响下一次判断
        fileName = "";
        return "forward:/prod/split";  //使用redirect会使上面的request提示回显失效，建议使用转发

    }

    @RequestMapping("/delete")
    public String delete(int pid, HttpServletRequest request) {
        int num = -1;
        try {
            num = productInfoService.delete(pid);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "删除成功");
        } else {
            request.setAttribute("msg", "删除失败");
        }
        return "forward:/prod/deleteAjax";
    }

    /**
     * 删除操作后需要跳转分页显示界面，现有的ajax分页处理方法没有返回值，不能传递删除操作是否成功的提示信息，
     * 删除操作使用了ajax方式，只局部刷新了table表格，没有刷新整个界面，因此不能使用<script>标签的信息弹框
     * 因为响应信息包含中文，所以需要指定编码
     */
    @RequestMapping(value = "/deleteAjax", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object deleteAjaxSplit(HttpServletRequest request) {
        PageInfo info = productInfoService.splitPage(1, PAGE_SIZE);
        request.getSession().setAttribute("info", info);
        return request.getAttribute("msg");

    }

    //批量删除商品
    @RequestMapping("deleteBatch")
    public String deleteBatch(String pids,HttpServletRequest request) {
        String[] ps = pids.split(",");

        try {
            int result = productInfoService.deleteBatch(ps);
            if (result > 0) {
                request.setAttribute("msg","批量删除成功");
            }else{
                request.setAttribute("msg","批量删除失败");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            request.setAttribute("msg","包含不可删除商品");
        }
        return "forward:/prod/deleteAjax";
    }




}





















